/**
 * 状态管理器模块
 * 提供全局状态管理功能，支持状态订阅、状态持久化等
 */

export class StateManager {
    constructor(options = {}) {
        this.state = {};
        this.listeners = new Map();
        this.history = [];
        this.maxHistorySize = options.maxHistorySize || 50;
        this.persistKey = options.persistKey || 'app_state';
        this.persistToStorage = options.persistToStorage !== false;
        
        // 初始化状态
        this.initializeState();
    }

    /**
     * 初始化状态
     */
    initializeState() {
        // 从本地存储恢复状态
        if (this.persistToStorage) {
            this.loadFromStorage();
        }
        
        // 设置默认状态
        this.state = {
            user: null,
            isAuthenticated: false,
            loading: false,
            notifications: [],
            ...this.state
        };
    }

    /**
     * 设置状态
     * @param {string|Object} key - 状态键或状态对象
     * @param {*} value - 状态值
     * @param {Object} options - 选项
     */
    setState(key, value, options = {}) {
        let stateChanges = {};
        
        if (typeof key === 'object') {
            // 如果key是对象，则合并到状态中
            stateChanges = key;
        } else {
            // 如果key是字符串，则设置单个状态
            stateChanges[key] = value;
        }
        
        // 记录历史
        if (options.recordHistory !== false) {
            this.recordHistory(stateChanges);
        }
        
        // 更新状态
        const prevState = { ...this.state };
        this.state = { ...this.state, ...stateChanges };
        
        // 持久化状态
        if (this.persistToStorage && options.persist !== false) {
            this.saveToStorage();
        }
        
        // 通知监听器
        this.notifyListeners(stateChanges, prevState);
        
        return this.state;
    }

    /**
     * 获取状态
     * @param {string} key - 状态键
     * @param {*} defaultValue - 默认值
     * @returns {*} - 状态值
     */
    getState(key, defaultValue = undefined) {
        if (key === undefined) {
            return { ...this.state };
        }
        
        return this.state[key] !== undefined ? this.state[key] : defaultValue;
    }

    /**
     * 订阅状态变化
     * @param {string|Function} key - 状态键或监听器函数
     * @param {Function} callback - 回调函数
     * @returns {Function} - 取消订阅函数
     */
    subscribe(key, callback) {
        let listener;
        
        if (typeof key === 'function') {
            // 如果第一个参数是函数，则监听所有状态变化
            listener = {
                key: null,
                callback: key
            };
        } else {
            // 否则监听特定键的状态变化
            listener = {
                key,
                callback
            };
        }
        
        // 生成监听器ID
        const id = generateId();
        listener.id = id;
        
        // 添加到监听器列表
        if (!this.listeners.has(id)) {
            this.listeners.set(id, listener);
        }
        
        // 返回取消订阅函数
        return () => {
            this.listeners.delete(id);
        };
    }

    /**
     * 取消订阅
     * @param {string|Function} id - 监听器ID或回调函数
     */
    unsubscribe(id) {
        if (typeof id === 'function') {
            // 如果是回调函数，查找对应的监听器
            for (const [listenerId, listener] of this.listeners.entries()) {
                if (listener.callback === id) {
                    this.listeners.delete(listenerId);
                    break;
                }
            }
        } else {
            // 否则直接删除监听器
            this.listeners.delete(id);
        }
    }

    /**
     * 通知监听器
     * @param {Object} stateChanges - 状态变化
     * @param {Object} prevState - 前一个状态
     */
    notifyListeners(stateChanges, prevState) {
        for (const listener of this.listeners.values()) {
            try {
                // 如果监听器没有指定键，或者状态变化包含监听的键
                if (!listener.key || Object.keys(stateChanges).includes(listener.key)) {
                    listener.callback(this.state, prevState, stateChanges);
                }
            } catch (error) {
                console.error('Error in state listener:', error);
            }
        }
    }

    /**
     * 记录状态历史
     * @param {Object} stateChanges - 状态变化
     */
    recordHistory(stateChanges) {
        this.history.push({
            timestamp: Date.now(),
            changes: { ...stateChanges },
            state: { ...this.state }
        });
        
        // 限制历史记录大小
        if (this.history.length > this.maxHistorySize) {
            this.history.shift();
        }
    }

    /**
     * 获取状态历史
     * @param {number} limit - 限制数量
     * @returns {Array} - 历史记录
     */
    getHistory(limit = this.maxHistorySize) {
        return this.history.slice(-limit);
    }

    /**
     * 撤销状态变化
     * @param {number} steps - 撤销步数
     * @returns {Object} - 当前状态
     */
    undo(steps = 1) {
        if (this.history.length < steps) {
            return this.state;
        }
        
        // 获取要撤销到的历史记录
        const targetHistory = this.history[this.history.length - steps];
        
        if (targetHistory) {
            // 恢复到目标状态
            this.state = { ...targetHistory.state };
            
            // 移除历史记录
            this.history = this.history.slice(0, -steps);
            
            // 持久化状态
            if (this.persistToStorage) {
                this.saveToStorage();
            }
            
            // 通知监听器
            this.notifyListeners({}, this.state);
        }
        
        return this.state;
    }

    /**
     * 重置状态
     * @param {Object} newState - 新状态
     * @returns {Object} - 当前状态
     */
    reset(newState = {}) {
        const prevState = { ...this.state };
        this.state = { ...newState };
        
        // 清空历史
        this.history = [];
        
        // 持久化状态
        if (this.persistToStorage) {
            this.saveToStorage();
        }
        
        // 通知监听器
        this.notifyListeners(this.state, prevState);
        
        return this.state;
    }

    /**
     * 保存状态到本地存储
     */
    saveToStorage() {
        try {
            const stateToSave = { ...this.state };
            
            // 过滤不需要持久化的状态
            if (stateToSave.loading !== undefined) {
                delete stateToSave.loading;
            }
            
            localStorage.setItem(this.persistKey, JSON.stringify(stateToSave));
        } catch (error) {
            console.error('Failed to save state to storage:', error);
        }
    }

    /**
     * 从本地存储加载状态
     */
    loadFromStorage() {
        try {
            const savedState = localStorage.getItem(this.persistKey);
            if (savedState) {
                this.state = { ...this.state, ...JSON.parse(savedState) };
            }
        } catch (error) {
            console.error('Failed to load state from storage:', error);
        }
    }

    /**
     * 清除状态
     */
    clear() {
        const prevState = { ...this.state };
        this.state = {};
        this.history = [];
        
        // 清除本地存储
        if (this.persistToStorage) {
            localStorage.removeItem(this.persistKey);
        }
        
        // 通知监听器
        this.notifyListeners({}, prevState);
    }

    /**
     * 创建状态选择器
     * @param {Function} selector - 选择器函数
     * @returns {Function} - 选择器函数
     */
    createSelector(selector) {
        return (state = this.state) => selector(state);
    }

    /**
     * 创建状态计算器
     * @param {Function} calculator - 计算器函数
     * @param {Array} dependencies - 依赖的状态键
     * @returns {Function} - 计算器函数
     */
    createCalculator(calculator, dependencies = []) {
        let cachedResult = null;
        let cachedDependencies = null;
        
        return (state = this.state) => {
            const currentDependencies = dependencies.map(key => state[key]);
            
            // 检查依赖是否变化
            if (
                !cachedDependencies ||
                !currentDependencies.every((dep, index) => dep === cachedDependencies[index])
            ) {
                cachedResult = calculator(state);
                cachedDependencies = currentDependencies;
            }
            
            return cachedResult;
        };
    }
}

/**
 * 生成唯一ID
 * @returns {string} - 唯一ID
 */
function generateId() {
    return `listener_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

// 创建默认状态管理器实例
export const stateManager = new StateManager();

// 导出默认状态管理器
export default stateManager;